<?php
namespace app\mobile\model;

use think\Db;
use think\Cookie;
use think\Request;
use think\Session;
use app\mobile\model\LotteryCode as LotteryCodeModel;

/**
 * Class Member
 * @package app\mobile\model 会员表
 */
class Member extends BaseModel
{
    /*
     * 登录检测
     */
    public function login_auth()
    {
        $request = Request::instance();
        if ($request->isPost()) {
            $data = $request->post();
            $arr = self::where(['username' => $data['username']])
                ->field('id,username,raw_id,password,shop_status')
                ->find();
            if ($arr) {
                if ($arr['password'] == md5(md5($data['password']))) {
                    //更改登录信息
                    $map['login_time'] = time();
                    $map['login_ip'] = $request->ip();
                    $this->where('id', $arr['id'])->update($map);
                    Session::set('member_id', $arr['id']);
                    //                    Cookie::set('member_id',$arr['id'],3600*24*7);  //设置7天免登陆
                    //检测是否是否绑定了手机
                    return ['code' => 200, 'message' => '登录成功'];

                } else {
                    return ['code' => 0, 'message' => '密码不正确'];
                }
            } else {
                return ['code' => 0, 'message' => '账号不存在'];
            }
        }
    }


    public function login_auth2()
    {
        $request = Request::instance();

        if ($request->isPost()) {

            // 获取数据
            $data = $request->post();

            $map = ['status' => 1];

            // 如果不存在cookie
            if (empty($_COOKIE['remember'])) {
                $map['username'] = $data['username'];
                $map['password'] = md5(md5($data['password']));

            } else {

                $mm = $_COOKIE['remember'];
                $nn = Db::name('member_a')->where('member_name', $mm)->value('key');
                if (!empty($nn)) {
                    $arr = explode(',', $nn);
                    $map['username'] = $arr[0];
                    $map['password'] = $arr[1];
                }

            }

            // 验证
            $find = self::where($map)->field('id,username,raw_id,password,shop_status')->find();

            if ($find) {
                $remrember = $request->param('remember');
                if ($remrember) {
                    setcookie('remember', "remember" . $find['id'], time() + 3600 * 24 * 365);

                    $nhk = Db::name('member_a')->where('member_name', "remember" . $find['id'])->value('id');
                    if ($nhk) {
                        $ini = [
                            'member_name' => "remember" . $find['id'],
                            'key'         => $map['username'] . "," . $map['password'],
                        ];
                        Db::name('member_a')->where('id', $nhk)->update($ini);
                    } else {
                        $ini = [
                            'member_name' => "remember" . $find['id'],
                            'key'         => $map['username'] . "," . $map['password'],
                        ];
                        Db::name('member_a')->insert($ini);
                    }


                } else {
                    setcookie('remember', null, time() - 3600 * 24 * 365);
                }

                // 更改登录状态 登录时间
                $con['login_time'] = time();
                $con['login_ip'] = $request->ip();
                $this->where('id', $find['id'])->update($map);
                Session::set('member_id', $find['id']);
                return ['code' => 200, 'message' => '登录成功'];

            } else {
                return ['code' => 0, 'message' => '账号或密码错误'];
            }


        }
    }

    /*
     * 会员注册
     */
    public function reg()
    {
        $request = Request::instance();
        $data = $request->post();
        // 注册信息
        $map['username'] = $data['username'];
        $map['password'] = sha1($data['password']);
        $map['create_time'] = date('Y-m-d H:i:s',time());
        //$map['create_ip'] = $request->ip();
        //$map['is_vip'] = 2;
        // 用户注册
       $member_id =  db('member')->insertGetId($map);

        // 如果没有上级会员
        $invit_id1 = $request->param('uid');
        $invit_id = $request->post('invit_id');

        //writeLog('id1'.$invit_id1);
       // writeLog('uidd'.$invit_id);
        //writeLog('uidjs'.json_encode($data));
        if (!$invit_id) {
            $invit_id = 0;
        }

       return self::distribution($invit_id, $member_id);

        //附加会员佣金表
        //self::add_brokerage($this->id);
        // // 生成抽奖码
        // self::create_lottery_code($this->id);
        return $member_id;
    }

    /**
     * 添加分销人
     * @param $referrals_id //上级id
     * @param $member_id //用户id(下级分销人)
     */
    public function distribution($referrals_id, $member_id)
    {

        $d = Db::name('message')->select();
        $member_list = Db::name('member')->select();
        $insertAll = [];
        if(!empty($d)){
            foreach ($d as $k1 =>  $v1){
                $insertAll[] = [
                    'member_id' => $member_id,
                    'title' => $v1['title'],
                    'content' => $v1['content'],
                    'create_time' => $v1['create_time'],
                    'message_id' => $v1['id']
                ];
            }
           (new MemberMessage())->insertAll($insertAll);
        }
        if($referrals_id){
            (new \app\index\controller\Coupon())->send(1,$referrals_id);
//            $coupon_info = Db::name('coupon')->where('id',65)->where('status',1)->order('id','asc')->find();
////            if($coupon_info['end_time'] <= time()){
////              // $coupon_info['end_time'] = time()+ 15552000;
////            }
//            if(!empty($coupon_info)){
//                $data = [
//                    'type' => $coupon_info['type'],
//                    'auding_status' => 2,
//                    'member_id' => $referrals_id,
//                    'coupon_id' => $coupon_info['id'],
//                    'title' => $coupon_info['title'],
//                    'minus_price' => $coupon_info['actual_price'],
//                    'total_price' => $coupon_info['virtual_price'],
//                    'content' => $coupon_info['content'],
//                    'start_time' => time(),
//                    'end_time' => $coupon_info['end_time'],
//                    'status' => $coupon_info['status'],
//                    'create_time' => date('Y-m-d H:i:s',time())
//                ];
//                Db::name('member_coupon')->insert($data);
//            }

        }
        if($member_id){
            (new \app\index\controller\Coupon())->send(2,$member_id);
//            $coupon_info2 = Db::name('coupon')->where('id',66)->where('status',1)->order('id','asc')->find();
////            if($coupon_info['end_time'] <= time()){
////              // $coupon_info['end_time'] = time()+ 15552000;
////            }
//            if(!empty($coupon_info2)){
//                $data2 = [
//                    'type' => $coupon_info2['type'],
//                    'auding_status' => 2,
//                    'member_id' => $member_id,
//                    'coupon_id' => $coupon_info2['id'],
//                    'title' => $coupon_info2['title'],
//                    'minus_price' => $coupon_info2['actual_price'],
//                    'total_price' => $coupon_info2['virtual_price'],
//                    'content' => $coupon_info2['content'],
//                    'start_time' => time(),
//                    'end_time' => $coupon_info2['end_time'],
//                    'status' => $coupon_info2['status'],
//                    'create_time' => date('Y-m-d H:i:s',time())
//                ];
//                Db::name('member_coupon')->insert($data2);
//            }
        }

        $find = Db::name('member_distribution')->where(['referrals_id' => $referrals_id])->fetchSql(false)->find();

        //writeLog('find'.$find);
        $new_distribution = '0,';
        $level = 1;

        //已有上级
        if ($find) {

            $new_distribution = $find['hierarchy'] . $find['referrals_id'] . ',';
            $level = (int)$find['level'] + 1;
        }

        $ini = [
            'distribution_id' => $referrals_id,   //分销人
            'referrals_id'    => $member_id,       //下线人
            'hierarchy'       => $new_distribution,   //层级
            'level'           => $level,   //级别
            'create_time'     => date('Y-m-d H:i:s',time()),
        ];

        (new MemberDistribution())->allowField(true)->save($ini);
    }

    /*
     * 会员表和会员收货地址一对多
     */
    public function memberAddress()
    {
        return $this->hasMany('MemberAddress', 'member_id', 'id');
    }

    /*
     * 会员和商品评价一对多
     */
    public function shopGoodsEvaluate()
    {
        return $this->hasMany('ShopGoodsEvaluate', 'member_id', 'id');
    }

    /*
     * 附加会员佣金表
     */
    public function add_brokerage($member_id)
    {
        $model = new MemberBrokerage();
        $map['member_id'] = $member_id;
        $map['general_income'] = 0;
        $map['to_yield'] = 0;
        $map['to_audit'] = 0;
        $map['actual_amount'] = 0;
        $model->save($map);
    }


}